package com.dk.logc.business;

import cn.hutool.core.date.DateUtil;
import com.dk.logc.config.CountFactory;
import com.dk.logc.domain.CountRole;
import com.dk.logc.domain.CountRoleSum;
import com.dk.logc.domain.FlogPayment;
import com.dk.logc.domain.GameRole;
import com.dk.logc.kafka.base.BaseRoleFlog;
import com.dk.logc.service.CountRoleService;
import com.dk.logc.service.CountRoleSumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @Author 林道敬
 * @Date 2024-01-11
 * @Description
 **/
@Component
@Slf4j
public class FlogPaymentBusiness implements SuperBusiness{
    @PostConstruct
    public void init(){
        CountFactory.register("payment",this);
    }
    @Autowired
    private GameRoleBusiness gameRoleBusiness;
    @Autowired
    private CountRoleService countRoleService;;
    @Autowired
    private CountRoleSumService countRoleSumService;

    @Transactional
    @Override
    public void progress(BaseRoleFlog baseRoleFlog, CountRole countRole, CountRoleSum countRoleSum) {
        FlogPayment flogPayment = (FlogPayment) baseRoleFlog;
        //角色不存在 不进行任何操作
        GameRole gameRole = gameRoleBusiness.getGameRole(flogPayment,"search payment");
        if(gameRole == null){
            return;
        }
        Date  createTime = gameRole.getCreateTime();
        String tablePrefix = createTime != null && DateUtil.isSameDay(new Date(), createTime) ? "new" : "old";
        gameRole.setLastPayTime(new Date());
        //更新用户数据
        gameRoleBusiness.saveOrUpdate(gameRole);
        //统计
        if(tablePrefix.equals("new")){
            countRole.setNewPayAmount(countRole.getNewPayAmount()+flogPayment.getCurrencyAmount());
            countRole.setNewPayNum(countRole.getNewPayNum()+1);
            countRoleSum.setTotalNewPayNum(countRoleSum.getTotalNewPayNum()+1);
            countRoleSum.setTotalNewPayAmount((int) (countRoleSum.getTotalNewPayAmount()+flogPayment.getCurrencyAmount()));
        }else {
            countRole.setOldPayNum(countRole.getOldPayNum()+1);
            countRole.setOldPayAmount(countRole.getOldPayAmount()+flogPayment.getCurrencyAmount());
            countRoleSum.setTotalOldPayNum(countRoleSum.getTotalOldPayNum()+1);
            countRoleSum.setTotalOldPayAmount((int) (countRoleSum.getTotalOldPayNum()+flogPayment.getCurrencyAmount()));
        }
        countRoleSumService.saveOrUpdate(countRoleSum);
        countRoleService.saveOrUpdate(countRole);
    }
}
